<template>
	<div class="c-upload">
		<div class="flex-center" style="flex-wrap: wrap;display: flex;">
			<div v-if="showAdd && list.length < max" class="add flex-box" :style="itemStyles"
				>
        <input type="file" :accept="accept" name="uploadFile" ref="upload"
          @change="getFile($event,list.length+1)" :multiple="multiplt">
				<slot name="add">
					<div>
            <img :class="[imgClass, 'disb']" :src="require('@/assets/img/add_card.png')" />
						<div class="el-upload__tip note mgt5 tac">{{ tips }}</div>
					</div>
				</slot>
			</div>
      <template v-if="list && list.length > 0">
        <div v-for="(item, index) in list" :key="index" class="item" :style="itemStyles">
          <div class="img">
            <img class="img" mode="aspectFit" :src="item" @click="preImg(item)"
                 v-if="item&&!previewShow"  />
            <!-- 预览图片-->
            <el-image
              v-else-if="item&&previewShow"
              class="img"
              mode="mode"
              lazy-load="true"
              :src="item"
              :preview-src-list="list">
            </el-image>
          </div>
          <div v-if="!readonly" class="del-warp flex-box zIndex1" @click="del(index)">
            <img class="img18 disb" :src="require('@/assets/img/auditIconUploadDelete.png')" />
          </div>
        </div>
      </template>
		</div>
    <div v-if="showTips" slot="tip" class="el-upload__tip">只能上传{{ accept }}文件，且不超过{{ maxSize }}M</div>

	</div>
</template>

<script>
	import config from '@/api/config.js';
	export default {
		name: 'c-upload',
		props: {
			readonly: {
				type: Boolean,
				default: false,
			},
			addIcon: {
				type: String,
				default: 'add_card.png',
			},
			delIcon: {
				type: String,
				default: 'auditIconUploadDelete.png',
			},
			canDelete: {
				type: Boolean,
				default: true,
			},
			showAdd: {
				type: Boolean,
				default: true,
			},
			value: {
				type: [Array, String],
				default: () => [],
			},
			max: {
				type: [Number, String],
				default: 1,
			},
			itemStyles: {
				type: [Object, String],
				default: '',
			},
			tips: {
				type: String,
				default: '',
			},
			// extraData: {
			// 	type: Object,
			// 	default: () => ({}),
			// },
			maxSize: {
				type: Number,
				default: 20,
			},
			filename: {
				type: String,
				default: 'image',
			},
      multiplt: {
        type: Number,
        default: 1,
      },
      // 预览图片
      previewShow:{
        type: Boolean,
        default: false
      },
      accept: {
        type: String,
        default: '.png, .jpg, .jpeg',
      },
      imgClass: {
        type: String,
        default: 'img36 disb',
      },
      //是否删除服务器数据
      deleteServe:{
        type: Boolean,
        default: false
      },
      showTips: {
        type: Boolean,
        default: true
      },
		},
		data() {
			return {
				list: [],
				resList: [],
        imagePrefix: config.imagePrefix
			};
		},
		computed: {
			maxSizeByte() {
				return this.maxSize * 1024;
			}
		},
		watch: {
			value: function(val) {
				this.list = val || [];
			},
			list: function(val) {
				this.$emit('input', val);
			},
		},
		created() {
			this.list = this.value;
      this.imagePrefix = config.imagePrefix
      if(this.list&&this.list.length>0){
        this.resList = this.list
      }else {
        this.resList = []
      }
		},
		methods: {
      // 清空已上传的文件列表
      clearFiles(){
        const vm = this
        vm.list = []
        vm.resList=vm.list;
      },
      clearFileList() {
        this.list = []
        this.resList=this.list;
      },
			del(index) {
        const vm = this
        if(!vm.deleteServe){
          vm.list = vm.list.splice(index, 1);
        }else {
          const file = this.list[index]
          vm.openFullScreen();
          vm.apiUrl.uploadDelete({
            file: file
          },"POST")
            .then(res => {
              vm.closeFullScreen(vm.openFullScreen());
              const { code,msg } = res;
              if (code != 0) {
                vm.showMessageMin({
                  type: 'error',
                  message: msg
                })
              } else {
                vm.showMessageMin({
                  type: 'success',
                  message: '文件已删除！'
                })
                this.list = this.list.splice(index, 1);
              }
            })
        }
			},
      getFile(event) {
        // console.log("event",event)
        const vm = this;
        if (vm.readonly) return;
        const max = vm.max - vm.list.length;
        let index = 0;
        let tempFilePaths = [];

        // 上传图片接口函数
        const uploadImage = () => {
        	if (index < tempFilePaths.length && index < max) {
        		this.upload.uploadFile(uploadData).then(res => {
        		  // console.log("res",res)
              const { code, data } = res
        		  if (code == 0) {
                if(this.openFullScreen()){
                  this.closeFullScreen(this.openFullScreen());
                }
        		    // this.$message('上传成功');
                if(data){
                  const url = data.f_url;
                  vm.list = vm.list.concat(url);
                  let arr = [];
                  if(vm.resList&&vm.resList.length>0){
                    arr = [...vm.resList];
                  }
                  arr[vm.list.length - 1] = data.f_url;
                  // vm.resList = arr;
                  //只拿路径value
                  vm.resList = Object.values(arr);
                  index++;
                  vm.$refs.upload.value = '';
                  uploadImage();
                }
        		  } else {
                if(this.openFullScreen()){
                  this.closeFullScreen(this.openFullScreen());
                }
        		    this.$message.error('上传失败');
        		  }

        		})
        	} else {
            if(this.openFullScreen()){
              this.closeFullScreen(this.openFullScreen());
            }
        		vm.$emit('complete', vm.resList);
        	}
        };

        // 系统上传方法处理
        var file = event.target.files;
        // 处理数据
        let uploadData = new FormData();
        // FormData传参用append()
        uploadData.append('filename', vm.filename);
        console.log('uploadData',uploadData)
        for (var i = 0; i < file.length; i++) {
          // 图片大小限制
          if(file[i].size/(1024*1024)>10){
            this.closeFullScreen(this.openFullScreen());
            this.$message.error("图片大小不能超过10M")
            return;
          }
          //    上传类型判断
          var imgName = file[i].name;
          var idx = imgName.lastIndexOf(".");
          if (idx != -1) {
            var ext = imgName.substr(idx + 1).toUpperCase();
            ext = ext.toLowerCase();
            const allow = vm.accept.replaceAll(' ','').split(',').includes('.'+ext)
            if (!allow) {
              vm.closeFullScreen(vm.openFullScreen());
              vm.showMessageMin({
                message: `只能上传${vm.accept}文件`,
                type: 'error'
              })
              return;
            }
            uploadData.append('file', file[i]);
            uploadData.append('maxSize', vm.maxSize);
            // if (ext != 'pdf' && ext != 'doc' && ext != 'docx') {
            //   uploadData.append('file', file[i]);
            // } else {
            //   uploadData.append('file', file[i]);
            // }
          }

        }

        // 筛选选择图片路径
        let tempFiles = [];
        tempFiles = tempFiles.concat(file)
        // console.log("tempFiles",tempFiles)
        if(tempFiles && tempFiles.length == 0) return;
        tempFilePaths = tempFiles.map((v) => v.name);
        // 最多可上传max张
        if (tempFilePaths.length > max) tempFilePaths = tempFilePaths.slice(0, max);
        if (!tempFilePaths.length) return;
        this.openFullScreen('上传中...');
        uploadImage();
      },
      // 预览图片
      preImg(e){

      }

		},
	};
</script>

<style lang="less" scoped>
  .c-upload{
    // margin-top: 30px;
  }

	.add,
	.item {
		box-sizing: border-box;
		width: 80px;
		height: 80px;
		// background: #f5f5f5;
		//border: 1px dotted #BCBCBC;
		border-radius: 5px;
		margin-right: 30px;
		margin-bottom: 20px;
		position: relative;

		&:nth-child(3n) {
			margin-right: 0;
		}
	}

  .add{

    input {
      position: absolute;
      z-index: 10;
      opacity: 0;
      width: 100%;
      height: 100%;
      top: 0;
      cursor: pointer;
    }
  }

	.img {
		width: 100%;
		height: 100%;
		display: block;
		// background: #000000;
	}

	.icon-delete {
		width: 18px;
		height: 18px;
		display: block;
		overflow: hidden;
		position: absolute;
		right: 14px;
		top: 14px;
	}

	.note {
		//color: rgba(188, 188, 188, 1);
	}

	.del-warp {
		width: 24px;
		height: 24px;
		/*background-color: #0A98D5;*/
		position: absolute;
		right: -14px;
		top: -14px;
	}
</style>
